﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TemplatesPrint.DBHelper;
using TemplatesPrint.Views;

namespace TemplatesPrint
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Process instance = RunningInstance();
            if (instance == null)
            {

                //设置应用程序处理异常方式：ThreadException处理  
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常  
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常  
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

                Application.ThreadExit += Application_ThreadExit;
                Application.ApplicationExit += Application_ApplicationExit;

                InitTable();
                InitT_Sql();

                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new FrmMain());
            }
            else
            {
                MessageBox.Show("已经启动了一个程序，请先退出！");
            }
        }

        static void InitT_Sql()
        {
            //try
            //{
            //if (System.IO.Directory.Exists(@"SourceSSql"))
            //{
            //    using (var db = MySqlHelper.GetInstance())
            //    {
            //        DirectoryInfo dirInfo = new DirectoryInfo("SourceSSql");
            //        FileInfo[] files = dirInfo.GetFiles();
            //        foreach (var f in files)
            //        {
            //            var sr = f.OpenText();
            //            string str = sr.ReadToEnd();
            //            db.Ado.ExecuteCommand(str);
            //            sr.Close();
            //            sr.Dispose();
            //            f.Delete();
            //        }
            //    };
            //}

            if (System.IO.Directory.Exists(@"SourceSql"))
            {
                using (var db = SQLiteHelper.GetInstance())
                {
                    DirectoryInfo dirInfo = new DirectoryInfo("SourceSql");
                    FileInfo[] files = dirInfo.GetFiles();
                    foreach (var f in files)
                    {
                        var sr = f.OpenText();
                        string str = sr.ReadToEnd();
                        db.Ado.ExecuteCommand(str);
                        sr.Close();
                        sr.Dispose();
                        f.Delete();
                    }
                };
            }
            //}
            //catch (Exception ex)
            //{

            //}
        }

        static void InitTable()
        {
            Assembly assembly = Assembly.LoadFrom(Application.StartupPath + @"\TemplatesPrint.exe");
            IEnumerable<Type> typelist = assembly.GetTypes().Where(c => c.FullName.StartsWith("TemplatesPrint.Entitys"));
            using (var db = SQLiteHelper.GetInstance())
            {
                bool Backup = true; //是否备份,实体变动时数据库更改表，并备份表
                if (Backup)
                {
                    db.CodeFirst.BackupTable().InitTables(typelist.ToArray());
                }
                else
                {
                    db.CodeFirst.InitTables(typelist.ToArray());
                }
            };
        }


        //不允许有两个程序同时启动
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //遍历正在有相同名字运行的例程 
            foreach (Process process in processes)
            {
                //忽略现有的例程 
                if (process.Id != current.Id)
                {
                    //确保例程从EXE文件运行 
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回另一个例程实例 
                        return process;
                    }
                }
            }
            //没有其它的例程，返回Null 
            return null;
        }

        static void Application_ApplicationExit(object sender, EventArgs e)
        {
            string str = e.ToString();
            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileStream fs = new FileStream("logFile\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Append);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + str + "\r\n");
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

        static void Application_ThreadExit(object sender, EventArgs e)
        {

            string str = e.ToString();
            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileStream fs = new FileStream("logFile\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Append);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + str + "\r\n");
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();


        }


        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileStream fs = new FileStream("logFile\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Append);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + str + "\r\n");
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();

        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            //MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileStream fs = new FileStream("logFile\\" + DateTime.Now.ToString("yyyyMMdd") + ".txt", FileMode.Append);
            //获得字节数组
            byte[] data = System.Text.Encoding.Default.GetBytes(DateTime.Now.ToString("yyyyMMdd HH:mm:ss") + str + "\r\n");
            //开始写入
            fs.Write(data, 0, data.Length);
            //清空缓冲区、关闭流
            fs.Flush();
            fs.Close();
        }

        /// <summary>  
        /// 生成自定义异常消息  
        /// </summary>  
        /// <param name="ex">异常对象</param>  
        /// <param name="backStr">备用异常消息：当ex为null时有效</param>  
        /// <returns>异常字符串文本</returns>  
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】：" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】：" + ex.GetType().Name);
                sb.AppendLine("【异常信息】：" + ex.Message);
                sb.AppendLine("【堆栈调用】：" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】：" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }
    }
}
